<template>
  <div class="recipe-list-page">
    <div class="page-header">
      <div class="header-content">
        <h2>食谱列表</h2>
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索食谱..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
      <el-button
        type="primary"
        :icon="Plus"
        @click="showAddDialog()"
      >
        添加食谱
      </el-button>
    </div>

    <div class="recipe-grid" v-loading="loading">
      <el-empty
        v-if="!recipes?.length"
        :description="searchKeyword ? '未找到相关食谱' : '暂无食谱'"
      />

      <el-row :gutter="20">
        <el-col
          v-for="recipe in recipes"
          :key="recipe.recipeId"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
        >
          <el-card 
            class="recipe-card" 
            shadow="hover"
            @click="viewRecipe(recipe.recipeId)"
          >
            <el-image
              :src="recipe.imageUrl"
              fit="cover"
              class="recipe-image"
            >
              <template #error>
                <div class="image-placeholder">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>

            <div class="recipe-info">
              <h3 class="recipe-name">{{ recipe.name }}</h3>
              <div class="recipe-stats">
                <span>
                  <el-icon><Timer /></el-icon>
                  {{ recipe.cookingTime }}分钟
                </span>
                <span>
                  <el-icon><Star /></el-icon>
                  {{ recipe.calories }}千卡
                </span>
              </div>
              <p class="recipe-description">{{ recipe.description }}</p>
            </div>

            <div class="recipe-actions" @click.stop>
              <el-button
                type="warning"
                text
                @click="showEditDialog(recipe)"
                :loading="recipe.editLoading"
              >
                编辑
              </el-button>
              <el-button
                type="success"
                text
                @click="showUploadDialog(recipe)"
              >
                上传图片
              </el-button>
              <el-button
                :type="recipe.favorite ? 'danger' : 'primary'"
                text
                @click="handleFavorite(recipe)"
                :loading="recipe.favoriteLoading"
              >
                {{ recipe.favorite ? '取消收藏' : '收藏' }}
              </el-button>
              <el-button
                type="danger"
                text
                @click="handleDelete(recipe)"
                :loading="recipe.deleteLoading"
              >
                删除
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 添加食谱弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingRecipe ? '编辑食谱' : '添加食谱'"
      width="800px"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="recipeForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="食谱名称" prop="name">
          <el-input v-model="recipeForm.name" />
        </el-form-item>

        <el-form-item label="烹饪时间" prop="cookingTime">
          <el-input-number v-model="recipeForm.cookingTime" :min="1" />
          <span class="unit">分钟</span>
        </el-form-item>

        <el-form-item label="难度" prop="difficulty">
          <el-select v-model="recipeForm.difficulty">
            <el-option label="简单" value="简单" />
            <el-option label="中等" value="中等" />
            <el-option label="困难" value="困难" />
          </el-select>
        </el-form-item>

        <el-form-item label="食谱简介" prop="description">
          <el-input
            v-model="recipeForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>

        <el-form-item label="食材配料">
          <div class="ingredients-list">
            <div
              v-for="(ingredient, index) in recipeForm.ingredients"
              :key="index"
              class="ingredient-item"
            >
              <el-select
                v-model="ingredient.foodId"
                placeholder="选择食材"
                filterable
                remote
                :remote-method="handleSearchFoods"
                :loading="foodsLoading"
                @change="(val) => handleFoodSelect(val, index)"
              >
                <el-option
                  v-for="food in foodOptions"
                  :key="food.foodId"
                  :label="food.name"
                  :value="food.foodId"
                />
              </el-select>
              <el-input-number
                v-model="ingredient.quantity"
                :min="0.1"
                :step="0.1"
                :precision="1"
              />
              <span class="unit">{{ ingredient.unit || '克' }}</span>
              <el-button
                type="danger"
                circle
                :icon="Delete"
                @click="removeIngredient(index)"
              />
            </div>
            <el-button
              type="primary"
              :icon="Plus"
              @click="addIngredient"
            >
              添加食材
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="烹饪步骤" prop="instructions">
          <el-input
            v-model="recipeForm.instructions"
            type="textarea"
            :rows="5"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="handleSubmit"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 添加图片上传弹窗 -->
    <el-dialog
      title="上传食谱图片"
      v-model="uploadDialogVisible"
      width="400px"
      :before-close="handleUploadDialogClose"
    >
      <div class="preview-container" v-if="previewUrl">
        <img :src="previewUrl" class="preview-image" />
      </div>
      <el-upload
        class="recipe-image-uploader"
        action="#"
        :show-file-list="true"
        :on-change="handleFileChange"
        :auto-upload="false"
        :limit="1"
        ref="uploadRef"
      >
        <el-button type="primary">选择图片</el-button>
        <template #tip>
          <div class="el-upload__tip">只能上传 jpg/png 文件，且不超过 2MB</div>
        </template>
      </el-upload>
      <template #footer>
        <el-button 
          @click="handleUploadDialogClose"
          :disabled="uploading"
        >
          取消
        </el-button>
        <el-button
          type="primary"
          :loading="uploading"
          :disabled="!tempImageFile || uploading"
          @click="handleUploadImage"
        >
          上传
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture, Timer, Star, Plus, Delete, Search } from '@element-plus/icons-vue'
import { getRecipes, addFavorite, removeFavorite, addRecipe, uploadRecipeImage, deleteRecipe, updateRecipe, searchRecipes } from '@/api/recipe'
import { searchFoods } from '@/api/food'

const router = useRouter()
const loading = ref(false)
const recipes = ref([])
const userId = localStorage.getItem('userId')

// 添加食谱相关
const dialogVisible = ref(false)
const editingRecipe = ref(null)
const formRef = ref(null)
const submitting = ref(false)
const foodsLoading = ref(false)
const foodOptions = ref([])
const tempImageFile = ref(null)

const uploadDialogVisible = ref(false)
const currentRecipe = ref(null)
const uploadRef = ref(null)
const uploading = ref(false)
const previewUrl = ref('')

const recipeForm = ref({
  name: '',
  cookingTime: 30,
  difficulty: '简单',
  description: '',
  ingredients: [{
    foodId: null,
    quantity: 100,
    unit: '克'
  }],
  instructions: ''
})

const rules = {
  name: [
    { required: true, message: '请输入食谱名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  cookingTime: [
    { required: true, message: '请输入烹饪时间', trigger: 'blur' },
    { type: 'number', min: 1, message: '烹饪时间必须大于0', trigger: 'blur' }
  ],
  difficulty: [
    { required: true, message: '请选择难度', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入食谱简介', trigger: 'blur' },
    { min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
  ],
  instructions: [
    { required: true, message: '请输入烹饪步骤', trigger: 'blur' },
    { min: 1, max: 1000, message: '长度在 1 到 1000 个字符', trigger: 'blur' }
  ],
  ingredients: {
    type: 'array',
    required: true,
    message: '请至少添加一种食材',
    trigger: 'change',
    validator: (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error('请至少添加一种食材'))
      } else {
        const invalidIngredients = value.some(
          item => !item.foodId || !item.name || item.quantity <= 0
        )
        if (invalidIngredients) {
          callback(new Error('请确保所有食材都已选择且用量大于0'))
        } else {
          callback()
        }
      }
    }
  }
}

// 搜索相关
const searchKeyword = ref('')
let searchTimer = null

// 处理搜索
const handleSearch = () => {
  // 清除之前的定时器
  if (searchTimer) {
    clearTimeout(searchTimer)
  }

  // 设置新的定时器，延迟 500ms 行搜索
  searchTimer = setTimeout(async () => {
    loading.value = true
    try {
      let response
      if (searchKeyword.value) {
        response = await searchRecipes({ keyword: searchKeyword.value })
      } else {
        response = await getRecipes({ userId: parseInt(userId) })
      }

      if (response?.success) {
        recipes.value = (response.data || []).map(recipe => ({
          ...recipe,
          favoriteLoading: false,
          deleteLoading: false,
          editLoading: false
        }))
      } else {
        recipes.value = []
        ElMessage.warning(response?.message || '搜索失败')
      }
    } catch (error) {
      console.error('搜索失败:', error)
      ElMessage.error('搜索失败')
      recipes.value = []
    } finally {
      loading.value = false
    }
  }, 500)
}

// 获取食谱列表
const fetchRecipes = async () => {
  loading.value = true
  try {
    const response = await getRecipes({ userId: parseInt(userId) })
    if (response?.success) {
      recipes.value = (response.data || []).map(recipe => ({
        ...recipe,
        favoriteLoading: false,
        deleteLoading: false,
        editLoading: false
      }))
    } else {
      recipes.value = []
      ElMessage.warning(response?.message || '获取食谱列表失败')
    }
  } catch (error) {
    console.error('获取食谱列表失败:', error)
    ElMessage.error('获取食谱列表失败')
    recipes.value = []
  } finally {
    loading.value = false
  }
}

// 查看食谱详情
const viewRecipe = (id) => {
  router.push(`/recipes/${id}`)
}

// 处理收藏/取消收藏
const handleFavorite = async (recipe) => {
  try {
    if (!userId) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    recipe.favoriteLoading = true

    if (recipe.favorite) {
      await removeFavorite(recipe.recipeId, { userId: parseInt(userId) })
      ElMessage.success('取消收藏成功')
    } else {
      const response = await addFavorite(recipe.recipeId, { userId: parseInt(userId) })
      if (!response?.success) {
        throw new Error(response?.message || '收藏失败')
      }
      ElMessage.success('收藏成功')
    }

    recipe.favorite = !recipe.favorite
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || (recipe.favorite ? '取消收藏失败' : '收藏失败'))
  } finally {
    recipe.favoriteLoading = false
  }
}

// 搜索食材
const handleSearchFoods = async (query) => {
  if (!query) {
    foodOptions.value = []
    return
  }

  foodsLoading.value = true
  try {
    const response = await searchFoods(query)
    if (response?.success) {
      foodOptions.value = response.data || []
    } else {
      foodOptions.value = []
      ElMessage.warning(response?.message || '搜索食材失败')
    }
  } catch (error) {
    console.error('搜索食材失败:', error)
    ElMessage.error('搜索食材失败')
    foodOptions.value = []
  } finally {
    foodsLoading.value = false
  }
}

// 处理食材选择
const handleFoodSelect = (foodId, index) => {
  const selectedFood = foodOptions.value.find(food => food.foodId === foodId)
  if (selectedFood) {
    recipeForm.value.ingredients[index] = {
      ...recipeForm.value.ingredients[index],
      foodId: Number(selectedFood.foodId),
      unit: selectedFood.unit || '克'
    }
  }
}

// 添加食材
const addIngredient = () => {
  recipeForm.value.ingredients.push({
    foodId: null,
    quantity: 100,
    unit: '单位'
  })
}

// 移除食材
const removeIngredient = (index) => {
  recipeForm.value.ingredients.splice(index, 1)
}

// 处理文件变化
const handleFileChange = (file) => {
  const isImage = file.raw.type.startsWith('image/')
  const isLt2M = file.raw.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  tempImageFile.value = file.raw
  previewUrl.value = URL.createObjectURL(file.raw)

  return false
}

// 处理图片上传
const handleUploadImage = async () => {
  if (!tempImageFile.value || !currentRecipe.value?.recipeId) {
    ElMessage.warning('请先选择图片')
    return
  }

  uploading.value = true
  try {
    const formData = new FormData()
    formData.append('file', tempImageFile.value)
    
    const response = await uploadRecipeImage(currentRecipe.value.recipeId, formData)
    
    if (response?.success) {
      ElMessage.success('图片上传成功')
      await fetchRecipes() // 刷新列表以显示新图片
      uploadDialogVisible.value = false
    } else {
      throw new Error(response?.message || '上传失败')
    }
  } catch (error) {
    console.error('上传图片失败:', error)
    ElMessage.error(error.message || '上传图片失败')
  } finally {
    uploading.value = false
  }
}

// 处理上传弹窗关闭
const handleUploadDialogClose = () => {
  if (uploading.value) {
    ElMessage.warning('正在上传中，请稍候...')
    return
  }
  uploadDialogVisible.value = false
  if (previewUrl.value && previewUrl.value.startsWith('blob:')) {
    URL.revokeObjectURL(previewUrl.value)
  }
  previewUrl.value = ''
  tempImageFile.value = null
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 显示上传图片弹窗
const showUploadDialog = (recipe) => {
  currentRecipe.value = recipe
  previewUrl.value = recipe.imageUrl || ''
  tempImageFile.value = null
  uploadDialogVisible.value = true
}

// 打开添加食谱对话框
const showAddDialog = () => {
  editingRecipe.value = null
  recipeForm.value = {
    name: '',
    cookingTime: 30,
    difficulty: '简单',
    description: '',
    ingredients: [{
      foodId: null,
      quantity: 1,
      unit: ''
    }],
    instructions: ''
  }
  dialogVisible.value = true
}

// 打开编辑食谱对话框
const showEditDialog = (recipe) => {
  try {
    recipe.editLoading = true
    editingRecipe.value = recipe
    recipeForm.value = {
      name: recipe.name,
      cookingTime: recipe.cookingTime,
      difficulty: recipe.difficulty,
      description: recipe.description,
      ingredients: (recipe.ingredients || []).map(item => ({
        foodId: item.foodId,
        quantity: item.quantity,
        unit: item.unit
      })) || [{
        foodId: null,
        quantity: 1,
        unit: ''
      }],
      instructions: recipe.instructions
    }
    dialogVisible.value = true
  } catch (error) {
    console.error('打开编辑对话框失败:', error)
    ElMessage.error('打开编辑对话框失败')
  } finally {
    recipe.editLoading = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    if (!recipeForm.value.ingredients?.length) {
      throw new Error('请至少添加一种食材')
    }

    // 验证所有食材都已选择
    const invalidIngredients = recipeForm.value.ingredients.some(
      item => !item.foodId || !item.quantity || item.quantity <= 0
    )
    if (invalidIngredients) {
      throw new Error('请确保所有食材都已选择且用量大于0')
    }

    // 准备提交的数据
    const formData = {
      name: recipeForm.value.name,
      cookingTime: Number(recipeForm.value.cookingTime),
      difficulty: recipeForm.value.difficulty,
      description: recipeForm.value.description,
      instructions: recipeForm.value.instructions,
      calories: 0,
      ingredients: recipeForm.value.ingredients
        .filter(item => item.foodId)
        .map(item => ({
          foodId: Number(item.foodId),
          quantity: Number(item.quantity),
          unit: item.unit || ''
        }))
    }

    let response
    if (editingRecipe.value) {
      response = await updateRecipe(editingRecipe.value.recipeId, {
        ...formData,
        recipeId: editingRecipe.value.recipeId
      })
    } else {
      response = await addRecipe(formData)
    }

    if (response?.success) {
      ElMessage.success(editingRecipe.value ? '更新成功' : '添加成功')
      dialogVisible.value = false
      await fetchRecipes()
    } else {
      throw new Error(response?.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

// 关闭对话框时处理
const handleClose = () => {
  formRef.value?.resetFields()
  editingRecipe.value = null
  recipeForm.value = {
    name: '',
    cookingTime: 30,
    difficulty: '简单',
    description: '',
    ingredients: [{
      foodId: null,
      quantity: 100,
      unit: '克'
    }],
    instructions: ''
  }
  dialogVisible.value = false
}

// 处理删除食谱
const handleDelete = async (recipe) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个食谱吗？此操作不可恢复。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    recipe.deleteLoading = true
    const response = await deleteRecipe(recipe.recipeId)

    if (response?.success) {
      ElMessage.success('删除成功')
      // 从列表中移除该食谱
      recipes.value = recipes.value.filter(item => item.recipeId !== recipe.recipeId)
    } else {
      throw new Error(response?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.info( '该食谱已被收藏无法删除')
    }
  } finally {
    recipe.deleteLoading = false
  }
}

onMounted(() => {
  fetchRecipes()
})
</script>

<style lang="scss" scoped>
.recipe-list-page {
  padding: 20px;

  .page-header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;

    .header-content {
      flex: 1;
      display: flex;
      align-items: center;
      gap: 16px;

      h2 {
        margin: 0;
        white-space: nowrap;
      }

      .search-box {
        flex: 1;
        max-width: 400px;
      }
    }
  }

  .recipe-grid {
    margin-bottom: 20px;
  }

  .recipe-card {
    margin-bottom: 20px;
    transition: transform 0.3s;
    cursor: pointer;

    &:hover {
      transform: translateY(-5px);
    }

    .recipe-image {
      width: 100%;
      height: 200px;
      border-radius: 4px;
      overflow: hidden;
    }

    .image-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: var(--el-fill-color-light);
      color: var(--el-text-color-secondary);
      font-size: 24px;
    }

    .recipe-info {
      padding: 12px 0;

      .recipe-name {
        margin: 0 0 8px;
        font-size: 16px;
        font-weight: bold;
      }

      .recipe-stats {
        display: flex;
        gap: 16px;
        color: var(--el-text-color-secondary);
        font-size: 14px;
        margin-bottom: 8px;

        span {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }

      .recipe-description {
        margin: 0;
        font-size: 14px;
        color: var(--el-text-color-regular);
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
    }

    .recipe-actions {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
      padding-top: 12px;
      border-top: 1px solid var(--el-border-color-lighter);
    }
  }

  .recipe-upload {
    width: 200px;
    height: 200px;
    border: 1px dashed var(--el-border-color);
    border-radius: 8px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    &:hover {
      border-color: var(--el-color-primary);
    }

    .upload-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .upload-icon {
      font-size: 28px;
      color: var(--el-text-color-secondary);
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .ingredients-list {
    .ingredient-item {
      display: flex;
      gap: 12px;
      margin-bottom: 12px;
      align-items: center;

      .el-select {
        flex: 1;
      }

      .unit {
        min-width: 30px;
        color: var(--el-text-color-regular);
      }
    }
  }

  .unit {
    margin-left: 8px;
    color: var(--el-text-color-secondary);
  }

  .upload-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: var(--el-text-color-secondary);

    .upload-icon {
      font-size: 28px;
      margin-bottom: 8px;
    }
  }

  .recipe-image-uploader {
    text-align: center;
    margin-bottom: 20px;
    
    .upload-content {
      width: 100%;
      height: 200px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .recipe-image {
      width: 200px;
      height: 200px;
      object-fit: cover;
      border-radius: 4px;
    }
    
    .upload-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 8px;
      color: var(--el-text-color-secondary);
      
      .recipe-uploader-icon {
        font-size: 28px;
      }
    }
  }

  .preview-container {
    text-align: center;
    margin-bottom: 20px;
    
    .preview-image {
      max-width: 100%;
      max-height: 300px;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
  }
}

@media (max-width: 768px) {
  .recipe-list-page {
    padding: 10px;

    .page-header {
      flex-direction: column;
      gap: 12px;

      .header-content {
        width: 100%;

        .search-box {
          max-width: none;
        }
      }
    }
  }
}
</style> 